<template>
  <div>
    <div class="tabBox">
      <Table :columns="tabCol" :data="allSku" :loading="isLoading"></Table>
    </div>
    <Modal v-model="showUserPrice" title="指定用户设置价格" width="600" :styles="{top: '8px'}" @on-ok="addUserPrice">
      <div style="margin-bottom: 16px;">
        检索用户：<Input v-model="phone" placeholder="根据电话号码查找用户" style="width: 200px;" @on-enter="searchUser"/>
        <Button type="primary" @click="searchUser">检索</Button>
      </div>
      <Form :model="priceForm" :label-width="50">
        <Row>
          <i-col span="6">
            <FormItem label="价格" prop="price">
              <InputNumber :min="0" v-model="priceForm.price"/>
            </FormItem>
          </i-col>
          <i-col span="6">
            <FormItem label="次数" prop="frequency">
              <InputNumber :min="0" v-model="priceForm.frequency"/>
            </FormItem>
          </i-col>
          <i-col span="12">
            <FormItem label="日期">
              <my-date-picker @dateChange="dateChange"></my-date-picker>
            </FormItem>
          </i-col>
        </Row>
      </Form>
      <div v-show="user[0]" style="overflow:hidden;">
        <h3>点击用户选中（选中背景为深色背景）</h3>
        <div v-for="(item, index) in user" :key="index" @click="clickUser(item, index)" class="user" :class="{select: index === activeIndex}">
          <Avatar :src="item.profilePhotoPath"></Avatar>
          <span>{{ item.nickname }}</span>
        </div>
      </div>
    </Modal>
    <Modal v-model="showUpdate" title="修改价格">
      <Row :gutter="16">
        <Form :label-width="80">
          <FormItem label="价格类型：">
            <RadioGroup v-model="discountType">
              <Radio :label="1">批量折扣</Radio>
              <Radio :label="2">指定价格</Radio>
              <Radio :label="3">一口价</Radio>
            </RadioGroup>
          </FormItem>
        </Form>
        <Form label-position="top" v-if="discountType === 2">
          <i-col span="8">
            <FormItem label="零售价（元）">
              <InputNumber v-model="retailPrice" :min="0.01"/>
            </FormItem>
          </i-col>
          <i-col span="8" v-for="(price, index) in updatePrice" :key="index">
            <FormItem :label="price.name + '（元）'">
              <InputNumber v-model="price.price" :min="0.01"/>
            </FormItem>
          </i-col>
        </Form>
        <Form v-else label-position="top">
          <FormItem label="零售价（元）">
            <InputNumber v-model="retailPrice" :min="0.01"/>
          </FormItem>
        </Form>
      </Row>
      <div slot="footer" style="text-align: center;">
        <Button type="primary" @click="subUpdate">完成修改</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import myDatePicker from '../../common/myDatePicker'
export default {
  name: 'goods-list-tab',
  data () {
    return {
      url: {
        skuUrl: '/goods/manage/get/goods/sku/by/goods',
        setPrice: '/discount/setup/manage/add/user/price',
        search: '/branch/user/search'
      },
      isLoading: true,
      tabCol: [
        {
          title: '货号',
          key: 'articleNumber',
          width: 80
        },
        {
          title: '商品',
          key: 'path',
          maxWidth: 180,
          render: (h, params) => {
            return h('div', [
              h('Avatar', {
                props: {
                  src: this.staticUrl + params.row.imagePath,
                  shape: 'square',
                  size: 'large'
                }
              }),
              h('span', params.row.goodsSkuName)
            ])
          }
        },
        {
          title: '库存类型',
          key: 'skuStockType',
          width: 100,
          render: (h, params) => {
            let str = ''
            switch (params.row.skuStockType) {
              case 1:
                str = '精准库存，不支持预定'
                break
              case 2:
                str = '精准库存，支持预定'
                break
              case 3:
                str = '无限量库存'
                break
            }
            return h('span', str)
          }
        },
        {
          title: '库存',
          key: 'stock',
          width: 100,
          render: (h, params) => {
            const _self = this
            return h('span', params.row.stock + _self.unit)
          }
        },
        {
          title: '预警库存',
          key: 'warningStock',
          width: 100,
          render: (h, params) => {
            const _self = this
            return h('span', {
              style: {
                fontWeight: '800',
                color: '#ed3f14'
              }
            }, params.row.warningStock + _self.unit)
          }
        },
        {
          title: '零售价',
          key: 'retailPrice',
          width: 100,
          render: (h, params) => {
            return h('span', params.row.retailPrice === 0 ? '----' : params.row.retailPrice / 100 + '￥')
          }
        },
        {
          title: '销量',
          key: 'sales',
          width: 100
        },
        {
          title: '排序',
          key: 'sortWeight',
          width: 70
        },
        {
          title: '价格',
          key: 'price',
          render: (h, params) => {
            return h('div', {
              style: {
                overflow: 'hidden'
              }
            }, [
              h('div', {
                style: {
                  float: 'left',
                  textAlign: 'right'
                }
              }, [
                params.row.price.map(value => {
                  return h('p', value.name + '：')
                })
              ]),
              h('div', {
                style: {
                  float: 'left'
                }
              }, [
                params.row.price.map(value => {
                  return h('p', value.price + '￥')
                })
              ])
            ])
          }
        },
        {
          title: '修改价格',
          width: 100,
          render: (h, params) => {
            return h('Button', {
              props: {
                size: 'small',
                type: 'primary'
              },
              on: {
                click: () => {
                  /*
                  * 分三种情况，体系价格、具体价格、一口价
                  * 1、区分三种价格走不同的策略
                  * 2、价格体系和一口价只能设置零售价，具体价格可以设置体系价格
                  * 3、数据结构：price: [{setupId, price, name}]
                  * 4、循环显示输入框
                  * 5、自定义提交按钮
                  * 6、显示弹出层
                  * */
                  this.toUpdatePrice(params.row)
                }
              }
            }, '修改价格')
          }
        },
        {
          title: '指定用户价格',
          key: 'setting',
          width: 80,
          render: (h, params) => {
            let _self = this
            return h('Button', {
              props: {
                type: 'primary',
                size: 'small'
              },
              on: {
                click: () => {
                  _self.setUserPrice(params.row)
                }
              }
            }, '设置')
          }
        }
      ],
      allSku: [],
      priceForm: {
        goodsSkuId: '',
        price: null,
        userId: null,
        endTime: 0,
        startTime: 0,
        frequency: null
      },
      showUserPrice: false,
      phone: '',
      user: [],
      activeIndex: null,

      setupName: [],
      showUpdate: false,
      updatePrice: [],
      updateId: null,
      discountType: null,
      retailPrice: null,
      oldPrice: '',
      nowRow: null
    }
  },
  props: ['id', 'unit', 'setups'],
  methods: {
    setUserPrice (row) {
      this.priceForm.goodsSkuId = row.goodsSkuId
      this.showUserPrice = true
    },
    dateChange (date) {
      this.priceForm.startTime = new Date(date[0]).valueOf()
      this.priceForm.endTime = new Date(date[1]).valueOf() + 24 * 3600 * 1000 - 1
    },
    clickUser (user, index) {
      this.activeIndex = index
      this.priceForm.userId = user.id
    },
    addUserPrice () {
      this.priceForm.price *= 100
      this.$ajax.post(this.url.setPrice, this.priceForm)
        .then(res => {
          if (res.data.success) {
            this.$Message.success('设置成功')
            this.showUserPrice = false
          }
        })
    },
    searchUser () {
      let params = {
        phone: this.phone,
        pageQuery: {
          pageNum: 1,
          pageSize: 30
        }
      }
      this.$ajax.post(this.url.search, JSON.stringify(params))
        .then(res => {
          if (res.data.success) {
            this.user = res.data.data.pageInfo.list
          }
        })
    },

    subUpdate () {
      /*
      * 提交修改之后的价格
      * 最终数据与priceJSON比较，得出修改过的价格，提交
      * */
      let params = {}
      if ((this.retailPrice && this.nowRow.retailPrice / 100 !== this.retailPrice) || this.nowRow.discountType !== this.discountType) {
        params.skuId = this.updateId
        params.discountType = this.discountType
        params.retailPrice = this.retailPrice * 100
        let isOk = true
        if (this.discountType === 2) {
          params.modifyGoodsPriceDtos = []
          this.updatePrice.forEach(item => {
            if (item.price) {
              params.modifyGoodsPriceDtos.push({
                branchCustomerId: item.setupId,
                price: item.price * 100
              })
            } else {
              isOk = false
            }
          })
        }
        if (isOk) {
          this.$ajax.post('/goods/manage/modify/retail/price', params)
            .then(res => {
              if (res.data.success) {
                this.$Message.success('更新成功')
                this.initList()
                this.showUpdate = false
              }
            })
        }
      }
    },
    toUpdatePrice (row) {
      /*
      * 1、得到修改商品id
      * 2、得到原始价格，与最后提交作比较
      * 3、得到该商品价格类型（有三种）
      * 4、显示输入框
      * */
      this.nowRow = row
      this.updateId = row.goodsSkuId
      this.discountType = row.discountType
      this.retailPrice = row.retailPrice / 100
      if (row.discountType === 1 || row.discountType === 3) {
        // 第一种和第三种只可以修改零售价
        this.updatePrice = []
        this.setups.forEach(item => {
          this.updatePrice.push({
            name: item.name,
            price: null,
            setupId: item.id
          })
        })
      } else if (row.discountType === 2) {
        // 第二种
        this.updatePrice = JSON.parse(JSON.stringify(row.price))
      }
      this.oldPrice = JSON.stringify(this.updatePrice)
      this.showUpdate = true
    },

    initList () {
      this.$ajax.get(this.url.skuUrl + '?goodsId=' + this.id).then(res => {
        let goods = []
        res.data.data.goodsSkuInfoList.forEach(item => {
          item.price = []
          goods[item.goodsSkuId] = item
        })
        res.data.data.gpsInfoList.sort((a, b) => {
          return (a.setupId - b.setupId)
        })
        res.data.data.gpsInfoList.forEach(item => {
          if (item.setupId === null) {
            goods[item.goodsSkuId].price.push({
              name: '一口价',
              price: item.afterDiscountPrice / 100
            })
          } else {
            goods[item.goodsSkuId].price.push({
              name: this.setupName['S' + item.setupId].name,
              price: item.afterDiscountPrice / 100,
              setupId: item.setupId
            })
          }
        })
        this.allSku = []
        for (let i in goods) {
          this.allSku.push(goods[i])
        }
        this.isLoading = false
      })
    }
  },
  components: {
    myDatePicker
  },
  created () {
    this.setups.forEach(item => {
      this.setupName['S' + item.id] = item
    })
    this.initList()
  }
}
</script>

<style scoped>
.tabBox{
  overflow: auto;
}
  .select{
    background-color: #dddee1;
  }
  .user{
    float: left;
    cursor: pointer;
    padding: 10px;
  }
</style>
